package cn.bluech.lib.persistent

import android.content.Context
import android.content.SharedPreferences
import java.lang.ClassCastException

class SpHandler(ctx: Context) {
    private val sp : SharedPreferences =
            ctx.getSharedPreferences(".default",Context.MODE_PRIVATE)


    fun put(key: String, value: Any?): SpHandler{
        if (null==value){
            remove(key)
            return this
        }

        val edit = sp.edit()
        when(value){
            Boolean   -> edit.putBoolean(key,value as Boolean)
            Int       -> edit.putInt(key, value as Int)
            Long      -> edit.putLong(key, value as Long)
            Float     -> edit.putFloat(key, value as Float)
            String    -> edit.putString(key, value as String?)
            // Set<String>
            is Set<*> -> edit.putStringSet(key, value as MutableSet<String>?)
            else ->{
            }
        }
        edit.apply()

        return this
    }

    fun getBoolean(key: String, defValue : Boolean?=false): Boolean{
        return try {
            sp.getBoolean(key,defValue ?: false)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue ?: false
        }
    }

    fun getInt(key: String, defValue : Int?=0): Int{
        return try {
            sp.getInt(key,defValue ?: 0)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue ?: 0
        }
    }

    fun getLong(key: String, defValue : Long?=0): Long{
        return try {
            sp.getLong(key,defValue ?: 0)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue ?: 0
        }
    }

    fun getFloat(key: String, defValue : Float?=0f): Float{
        return try {
            sp.getFloat(key,defValue ?: 0f)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue ?: 0f
        }
    }

    fun getString(key: String, defValue : String?=null): String?{
        return try {
            sp.getString(key,defValue)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue
        }
    }

    fun getStringSet(key: String, defValue : Set<String>?=null): Set<String>?{
        return try {
            sp.getStringSet(key,defValue)
        }catch (e:ClassCastException){
            e.printStackTrace()
            defValue
        }
    }

    fun contains(key: String): Boolean{
        return contains(key)
    }

    fun remove(key: String): SpHandler{
        sp.edit().remove(key).apply()
        return this
    }

    fun clear(){
        sp.edit().clear().apply()
    }

}